package com.yzy.fly.loader;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzy.fly.entity.core.*;
import com.yzy.fly.mapper.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class ClassInfoLoader {
    @Autowired
    private FlyClassAnnotationMapper flyClassAnnotationMapper;
    @Autowired
    private FlyFieldAnnotationMapper flyFieldAnnotationMapper;
    @Autowired
    private FlyClassMapper flyClassMapper;
    @Autowired
    private FlyFieldMapper flyFieldMapper;
    @Autowired
    private FlySqlMapper flySqlMapper;

//    @Autowired
//    private RedisTemplate<Object, Environment> environmentRedisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private static StringRedisTemplate staticStringRedisTemplate;

    private Set<String> sinkKeySet = new HashSet<>();
    @PostConstruct
    public void init() {
        staticStringRedisTemplate = stringRedisTemplate;
    }

    public List<FlyClass> loader() {
        List<FlyClass> flyClasses = flyClassMapper.selectAll();
        for (int i = 0; i < flyClasses.size(); i++) {
            FlyClass flyClass =  flyClasses.get(i);
            Integer classId = flyClass.getId();

            QueryWrapper<FlyClassAnnotation> flyClassAnnotationQueryWrapper = new QueryWrapper<>();
            flyClassAnnotationQueryWrapper.eq("classId",classId);
//            List<FlyClassAnnotation> annotationList = flyClassAnnotationMapper.selectAllByClassId(classId);
            List<FlyClassAnnotation> annotationList = flyClassAnnotationMapper.selectList(flyClassAnnotationQueryWrapper);
            flyClass.setAnnotationList(annotationList);
            List<FlyField> fieldList = flyFieldMapper.selectAllByClassId(classId);
            QueryWrapper<FlySql> flySqlQueryWrapper = new QueryWrapper<>();
            flySqlQueryWrapper.eq("classId",classId);
//            List<FlySql> sqlList = flySqlMapper.selectAllByClassId(classId);
//            List<FlySql> sqlList = flySqlMapper.selectList(flySqlQueryWrapper);
            if (CollectionUtils.isNotEmpty(fieldList)) {
                for (int j = 0; j < fieldList.size(); j++) {
                    FlyField flyField =  fieldList.get(j);
                    QueryWrapper<FlyFieldAnnotation> flyFieldAnnotationQueryWrapper = new QueryWrapper<>();
                    flyFieldAnnotationQueryWrapper.eq("fieldId",flyField.getId());
//                    List<FlyFieldAnnotation> flyFieldAnnotations = flyFieldAnnotationMapper.selectAllByFieldId(flyField.getId());
                    List<FlyFieldAnnotation> flyFieldAnnotations = flyFieldAnnotationMapper.selectList(flyFieldAnnotationQueryWrapper);
                    flyField.setAnnotationList(flyFieldAnnotations);
                }
                flyClass.setFieldList(fieldList);
            }
            if (CollectionUtils.isNotEmpty(fieldList)) {
//                flyClass.setSqlList(sqlList);
            }

        }
        return flyClasses;

//        Environment envEntity = null;
//        String cacheKey = "envCache";
//        String sinkKeyCache = "sinkKeyCache";
//        try {
//            if (environmentRedisTemplate.hasKey(cacheKey)) {
//                envEntity = environmentRedisTemplate.opsForValue().get(cacheKey);
//            } else {
//                List<Environment> envs = environmentMapper.selectAllByIp(IPUtil.LOCAL_HOST_IP);
//                envEntity = assemble(envs.get(0));
//                environmentRedisTemplate.opsForValue().set(cacheKey,envEntity,1L, TimeUnit.MINUTES);
//
//                stringRedisTemplate.opsForSet().add(sinkKeyCache,sinkKeySet.toArray(new String[sinkKeySet.size()]));
//
//            }
//        }catch (RedisConnectionFailureException|RedisConnectionException e) {
////            e.printStackTrace();
//            throw new Exception("Redis缓存服务器连接失败,请检查 "+e.getMessage());
//        }catch (Exception e) {
//            e.printStackTrace();
//            throw new Exception("配置信息执行异常,请检查 "+e.getMessage());
//        }
//        return envEntity;
    }

//    private Environment assemble(Environment envEntity) {
//        Integer id = envEntity.getId();
//        QueryWrapper jobQueryWrapper = new QueryWrapper<>();
//        jobQueryWrapper.eq("envId",id);
//        List<Job> jobs = jobMapper.selectList(jobQueryWrapper);
////        List<Job> jobs = jobMapper.selectAllByEnvId(id);
//        if (CollectionUtils.isNotEmpty(jobs)) {
//            envEntity.setJobList(jobs);
//            for (int i = 0; i < jobs.size(); i++) {
//                Job com.yzy.fly.funtion.job =  jobs.get(i);
//
//                QueryWrapper streamQueryWrapper = new QueryWrapper<>();
//                streamQueryWrapper.eq("jobId",com.yzy.fly.funtion.job.getId());
//                List<Stream> streams = streamMapper.selectList(streamQueryWrapper);
////                List<Stream> streams = streamMapper.selectAllByJobId(com.yzy.fly.funtion.job.getId());
//                for (int j = 0; j < streams.size(); j++) {
//                    Stream stream = streams.get(j);
//                    String streamParentNo = stream.getParentNo();
//                    if (StringUtils.isBlank(streamParentNo)) {
//                        streamParentNo = "";
//                    }
//                    sinkKeySet.add(streamParentNo + stream.getNo());
//
//                    List<Config> configs = configMapper.selectAllByStreamId(stream.getId());
//                    List<Config> assemble = assemble(configs);
//                    if (CollectionUtils.isNotEmpty(assemble)) {
//                        stream.setConfig(assemble.get(0));
//                    }
////                    List<Sink> sinks = sinkMapper.selectAllByStreamId(stream.getId());
//                    QueryWrapper sinkQueryWrapper = new QueryWrapper<>();
//                    sinkQueryWrapper.eq("streamId",stream.getId());
//                    List<Sink> sinks = sinkMapper.selectList(sinkQueryWrapper);
//                    if (CollectionUtils.isNotEmpty(sinks)) {
//                        stream.setSink(sinks.get(0));
//                    }
//
//                    QueryWrapper filterQueryWrapper = new QueryWrapper<>();
//                    filterQueryWrapper.eq("streamId",stream.getId());
//                    List<Filter> filters = filterMapper.selectList(filterQueryWrapper);
//                    if (CollectionUtils.isNotEmpty(filters)) {
//                        stream.setFilter(filters.get(0));
//                    }
//                }
//                List<Stream> assemble = assemble2(streams);
//                if (CollectionUtils.isNotEmpty(assemble)) {
//                    com.yzy.fly.funtion.job.setStreamList(assemble);
//                }
//            }
//        }
//        return envEntity;
//    }

//    private List<Config> assemble(List<Config> configs) {
//        if (CollectionUtils.isEmpty(configs)) {
//            return null;
//        }
//
//        List<Config> parentConfigs = new ArrayList<>();
//        List<Config> normalConfigs = new ArrayList<>();
//
//        if (CollectionUtils.isEmpty(configs)) {
//            return null;
//        } else {
//            for (int i = 0; i < configs.size(); i++) {
//                Config config =  configs.get(i);
//                Integer parentId = config.getParentId();
//                if (parentId == null || parentId.intValue() == 0) {
//                    parentConfigs.add(config);
//                } else {
//                    normalConfigs.add(config);
//                }
//                if (FieldTypeSimple.DOUBLE.toString().equals(config.getFieldType().toUpperCase())) {
//                    List<Level> levels = levelMapper.selectAllByConfigId(config.getId());
//                    config.setLevelList(levels);
//                }
//            }
//        }
//        assembleDetail(parentConfigs,normalConfigs);
//        return parentConfigs;
//    }
//
//    private List<Stream> assemble2(List<Stream> configs) {
//        if (CollectionUtils.isEmpty(configs)) {
//            return null;
//        }
//
//        List<Stream> parentConfigs = new ArrayList<>();
//        List<Stream> normalConfigs = new ArrayList<>();
//
//        if (CollectionUtils.isEmpty(configs)) {
//            return null;
//        } else {
//            for (int i = 0; i < configs.size(); i++) {
//                Stream config =  configs.get(i);
//                Integer parentId = config.getParentId();
//                if (parentId == null || parentId.intValue() == 0) {
//                    parentConfigs.add(config);
//                } else {
//                    normalConfigs.add(config);
//                }
//            }
//        }
//        assembleDetail2(parentConfigs,normalConfigs);
//        return parentConfigs;
//    }
//    private void assembleDetail2(List<Stream> rootConfigs,List<Stream> subConfigs) {
//        //装配
//        for (int i = 0; i < rootConfigs.size(); i++) {
//            Stream config =  rootConfigs.get(i);
//            if (CollectionUtils.isNotEmpty(subConfigs)) {
//                List<Stream> tempList = new ArrayList<>();
//                for (int j = subConfigs.size() -1; j>=0 ; j--) {
//                    Stream subConfig = subConfigs.get(j);
//                    if (subConfig.getParentId().intValue() == config.getId().intValue()) {
//                        tempList.add(subConfig);
//                        subConfigs.remove(subConfig);
//                    }
//                }
//
//                if (CollectionUtils.isNotEmpty(tempList)) {
//                    config.setStreamList(tempList);
//                    assembleDetail2(tempList,subConfigs);
//                }
//            }
//        }
//    }
//
//
//    private void assembleDetail(List<Config> rootConfigs,List<Config> subConfigs) {
//        //装配
//        for (int i = 0; i < rootConfigs.size(); i++) {
//            Config config =  rootConfigs.get(i);
//
//            if (config.getParentId() != null) {
//                sinkKeySet.add(config.getParentNo()+"."+config.getNo());
//            }
//
//            if (CollectionUtils.isNotEmpty(subConfigs)) {
//                List<Config> tempList = new ArrayList<>();
//                for (int j = subConfigs.size() -1; j>=0 ; j--) {
//                    Config subConfig = subConfigs.get(j);
//                    if (subConfig.getParentId().intValue() == config.getId().intValue()) {
//                        tempList.add(subConfig);
//                        sinkKeySet.add(subConfig.getParentNo()+"."+subConfig.getNo());
//                        subConfigs.remove(subConfig);
//                    }
//                }
//
//                if (CollectionUtils.isNotEmpty(tempList)) {
//                    config.setConfigList(tempList);
//                    assembleDetail(tempList,subConfigs);
//                }
//            }
//
//            if (FieldTypeSimple.DOUBLE.toString().equals(config.getFieldType().toUpperCase())) {
//                List<Level> levels = levelMapper.selectAllByConfigId(config.getId());
//                config.setLevelList(levels);
//            }
//        }
//    }

//    public static void main(String[] args) {
//
////        String str = "[1,3,5,6,7,8]";
//        String str = "{\"name\":\"32432\",age:132}";
////        String str = "[{\"name\":\"32432\",age:132},{\"name\":\"32432\",age:132},{\"name\":\"32432\",age:132},{\"name\":\"32432\",age:132},{\"name\":\"32432\",age:132}]";
//
//        Object parse = JSON.parse(str);
//        if (parse instanceof JSONObject) {
//            (JSONObject)parse;
//        } else if (parse instanceof JSONArray) {
//
//        }
//
//        Object jsonObject = sa.get(0);
//        int s =0;
//
//
//    }
}
